// 表格主题配色方案
const TABLE_THEMES = {
  default: {
    name: '默认蓝紫',
    colors: {
      primary: '#6366f1',
      secondary: '#764ba2',
      accent: '#4facfe'
    }
  },
  green: {
    name: '清新绿色',
    colors: {
      primary: '#22c55e',
      secondary: '#10b981',
      accent: '#059669'
    }
  },
  orange: {
    name: '温暖橙色',
    colors: {
      primary: '#fb923c',
      secondary: '#f97316',
      accent: '#ea580c'
    }
  },
  red: {
    name: '活力红色',
    colors: {
      primary: '#ef4444',
      secondary: '#dc2626',
      accent: '#b91c1c'
    }
  },
  purple: {
    name: '优雅紫色',
    colors: {
      primary: '#9333ea',
      secondary: '#7c3aed',
      accent: '#6d28d9'
    }
  },
  blue: {
    name: '冷静蓝色',
    colors: {
      primary: '#3b82f6',
      secondary: '#2563eb',
      accent: '#1d4ed8'
    }
  },
  pink: {
    name: '甜美芭比粉',
    colors: {
      primary: '#FF6B9D',
      secondary: '#FF8FAB',
      accent: '#E056B5'
    }
  }
}

// 处理主题样式
export function handleThemeStyle(theme) {
	document.documentElement.style.setProperty('--el-color-primary', theme)
	for (let i = 1; i <= 9; i++) {
		document.documentElement.style.setProperty(`--el-color-primary-light-${i}`, `${getLightColor(theme, i / 10)}`)
	}
	for (let i = 1; i <= 9; i++) {
		document.documentElement.style.setProperty(`--el-color-primary-dark-${i}`, `${getDarkColor(theme, i / 10)}`)
	}
}

// 处理表格主题样式
export function handleTableTheme(themeKey = 'default', isDark = false) {
	const theme = TABLE_THEMES[themeKey] || TABLE_THEMES.default
	const { primary, secondary, accent } = theme.colors
	
	// 转换为RGB值用于透明度计算
	const primaryRgb = hexToRgb(primary)
	const secondaryRgb = hexToRgb(secondary)
	const accentRgb = hexToRgb(accent)
	
	if (isDark) {
		// 暗黑模式表格主题
		document.documentElement.style.setProperty(
			'--table-bg-gradient-dark',
			`linear-gradient(135deg, 
				rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.05) 0%, 
				rgba(${secondaryRgb[0]}, ${secondaryRgb[1]}, ${secondaryRgb[2]}, 0.05) 50%,
				rgba(${accentRgb[0]}, ${accentRgb[1]}, ${accentRgb[2]}, 0.05) 100%)`
		)
		document.documentElement.style.setProperty(
			'--table-header-bg-gradient-dark',
			`linear-gradient(135deg, 
				rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.12) 0%, 
				rgba(${secondaryRgb[0]}, ${secondaryRgb[1]}, ${secondaryRgb[2]}, 0.12) 50%,
				rgba(${accentRgb[0]}, ${accentRgb[1]}, ${accentRgb[2]}, 0.12) 100%)`
		)
		document.documentElement.style.setProperty(
			'--table-row-hover-bg-gradient-dark',
			`linear-gradient(135deg, 
				rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.15) 0%, 
				rgba(${secondaryRgb[0]}, ${secondaryRgb[1]}, ${secondaryRgb[2]}, 0.15) 100%)`
		)
		document.documentElement.style.setProperty(
			'--table-row-bg-gradient-dark',
			`linear-gradient(135deg, 
				rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.03) 0%, 
				rgba(${secondaryRgb[0]}, ${secondaryRgb[1]}, ${secondaryRgb[2]}, 0.03) 100%)`
		)
		document.documentElement.style.setProperty(
			'--table-row-even-bg-gradient-dark',
			`linear-gradient(135deg, 
				rgba(${accentRgb[0]}, ${accentRgb[1]}, ${accentRgb[2]}, 0.05) 0%, 
				rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.05) 100%)`
		)
		document.documentElement.style.setProperty(
			'--table-border-color-dark',
			`rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.2)`
		)
		document.documentElement.style.setProperty(
			'--table-header-border-color-dark',
			`rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.25)`
		)
		document.documentElement.style.setProperty(
			'--table-cell-border-color-dark',
			`rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.15)`
		)
	} else {
		// 浅色模式表格主题
		document.documentElement.style.setProperty(
			'--table-bg-gradient',
			`linear-gradient(135deg, 
				rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.02) 0%, 
				rgba(${secondaryRgb[0]}, ${secondaryRgb[1]}, ${secondaryRgb[2]}, 0.02) 50%,
				rgba(${accentRgb[0]}, ${accentRgb[1]}, ${accentRgb[2]}, 0.02) 100%)`
		)
		document.documentElement.style.setProperty(
			'--table-header-bg-gradient',
			`linear-gradient(135deg, 
				rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.08) 0%, 
				rgba(${secondaryRgb[0]}, ${secondaryRgb[1]}, ${secondaryRgb[2]}, 0.08) 50%,
				rgba(${accentRgb[0]}, ${accentRgb[1]}, ${accentRgb[2]}, 0.08) 100%)`
		)
		document.documentElement.style.setProperty(
			'--table-row-hover-bg-gradient',
			`linear-gradient(135deg, 
				rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.1) 0%, 
				rgba(${secondaryRgb[0]}, ${secondaryRgb[1]}, ${secondaryRgb[2]}, 0.1) 100%)`
		)
		document.documentElement.style.setProperty(
			'--table-row-bg-color',
			`rgba(255, 255, 255, 0.5)`
		)
		document.documentElement.style.setProperty(
			'--table-row-even-bg-color',
			`rgba(248, 250, 252, 0.7)`
		)
		document.documentElement.style.setProperty(
			'--table-border-color',
			`rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.15)`
		)
		document.documentElement.style.setProperty(
			'--table-header-border-color',
			`rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.2)`
		)
		document.documentElement.style.setProperty(
			'--table-cell-border-color',
			`rgba(${primaryRgb[0]}, ${primaryRgb[1]}, ${primaryRgb[2]}, 0.1)`
		)
		document.documentElement.style.setProperty(
			'--table-header-text-color',
			'#475569'
		)
	}
}

// 初始化表格主题默认值
export function initDefaultTableTheme() {
	const isDark = document.documentElement.classList.contains('dark')
	
	if (isDark) {
		// 暗黑模式默认值
		document.documentElement.style.setProperty(
			'--table-bg-gradient-dark',
			'linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 50%, rgba(79, 172, 254, 0.05) 100%)'
		)
		document.documentElement.style.setProperty(
			'--table-header-bg-gradient-dark',
			'linear-gradient(135deg, rgba(102, 126, 234, 0.12) 0%, rgba(118, 75, 162, 0.12) 50%, rgba(79, 172, 254, 0.12) 100%)'
		)
		document.documentElement.style.setProperty(
			'--table-row-hover-bg-gradient-dark',
			'linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.15) 100%)'
		)
		document.documentElement.style.setProperty(
			'--table-row-bg-gradient-dark',
			'linear-gradient(135deg, rgba(102, 126, 234, 0.03) 0%, rgba(118, 75, 162, 0.03) 100%)'
		)
		document.documentElement.style.setProperty(
			'--table-row-even-bg-gradient-dark',
			'linear-gradient(135deg, rgba(79, 172, 254, 0.05) 0%, rgba(102, 126, 234, 0.05) 100%)'
		)
	} else {
		// 浅色模式默认值
		document.documentElement.style.setProperty(
			'--table-bg-gradient',
			'linear-gradient(135deg, rgba(102, 126, 234, 0.02) 0%, rgba(118, 75, 162, 0.02) 50%, rgba(79, 172, 254, 0.02) 100%)'
		)
		document.documentElement.style.setProperty(
			'--table-header-bg-gradient',
			'linear-gradient(135deg, rgba(102, 126, 234, 0.08) 0%, rgba(118, 75, 162, 0.08) 50%, rgba(79, 172, 254, 0.08) 100%)'
		)
		document.documentElement.style.setProperty(
			'--table-row-hover-bg-gradient',
			'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)'
		)
		document.documentElement.style.setProperty(
			'--table-row-bg-color',
			'rgba(255, 255, 255, 0.5)'
		)
		document.documentElement.style.setProperty(
			'--table-row-even-bg-color',
			'rgba(248, 250, 252, 0.7)'
		)
		document.documentElement.style.setProperty(
			'--table-border-color',
			'rgba(102, 126, 234, 0.15)'
		)
		document.documentElement.style.setProperty(
			'--table-header-border-color',
			'rgba(102, 126, 234, 0.2)'
		)
		document.documentElement.style.setProperty(
			'--table-cell-border-color',
			'rgba(102, 126, 234, 0.1)'
		)
		document.documentElement.style.setProperty(
			'--table-header-text-color',
			'#475569'
		)
	}
}

// 处理页面背景色
export function handlePageBackgroundStyle(color, isDark) {
	if (isDark) {
		const darkBg = '#000000' // 改为纯黑色
		document.documentElement.style.setProperty('--main-bg-color', darkBg)
		document.body.style.background = darkBg
		// 为暗黑模式设置额外的背景样式
		document.body.style.setProperty('background', darkBg, 'important')
	} else {
		// 使用纯色背景，不使用渐变
		document.documentElement.style.setProperty('--main-bg-color', color)
		document.body.style.background = color
		// 强制应用背景色，确保优先级
		document.body.style.setProperty('background', color, 'important')
		
		// 更新所有相关的页面背景元素
		const selectors = [
			'.app-main',
			'.modern-app-main', 
			'.page-content',
			'.page-container',
			'.main-container',
			'.app-wrapper',
			'.ultra-wide-layout',
			'.app-container'
		]
		
		selectors.forEach(selector => {
			const elements = document.querySelectorAll(selector)
			elements.forEach(element => {
				element.style.setProperty('background-color', color, 'important')
			})
		})
		
		// 更新CSS变量 - 添加更多变量覆盖
		const root = document.documentElement
		root.style.setProperty('--page-bg-color', color)
		root.style.setProperty('--app-bg-color', color)
		root.style.setProperty('--color-gray-50', color)  // 覆盖默认灰色
		root.style.setProperty('--main-container-bg', color)
		root.style.setProperty('--app-wrapper-bg', color)
	}
}

// 根据主题颜色自动选择表格主题
export function getTableThemeFromPrimaryColor(primaryColor) {
	const colorMap = {
		'#22c55e': 'green',
		'#10b981': 'green', 
		'#fb923c': 'orange',
		'#f97316': 'orange',
		'#ef4444': 'red',
		'#dc2626': 'red',
		'#9333ea': 'purple',
		'#7c3aed': 'purple',
		'#3b82f6': 'blue',
		'#2563eb': 'blue',
		'#FF6B9D': 'pink',
		'#FF8FAB': 'pink',
		'#E056B5': 'pink'
	}
	
	// 检查完全匹配
	if (colorMap[primaryColor]) {
		return colorMap[primaryColor]
	}
	
	// 检查颜色相似度（简单的RGB距离）
	const targetRgb = hexToRgb(primaryColor)
	let closestTheme = 'default'
	let minDistance = Infinity
	
	Object.entries(TABLE_THEMES).forEach(([key, theme]) => {
		const themeRgb = hexToRgb(theme.colors.primary)
		const distance = Math.sqrt(
			Math.pow(targetRgb[0] - themeRgb[0], 2) +
			Math.pow(targetRgb[1] - themeRgb[1], 2) +
			Math.pow(targetRgb[2] - themeRgb[2], 2)
		)
		
		if (distance < minDistance) {
			minDistance = distance
			closestTheme = key
		}
	})
	
	return closestTheme
}

// 应用完整主题样式
export function applyFullTheme(theme, isDark = false) {
	if (!theme) return
	
	// 先初始化默认表格主题
	initDefaultTableTheme()
	
	// 应用页面背景色
	handlePageBackgroundStyle(theme.background, isDark)
	
	// 根据主题自动选择表格配色
	const tableTheme = getTableThemeFromPrimaryColor(theme.navbar || theme.sidebar || '#6366f1')
	handleTableTheme(tableTheme, isDark)
	
	// 延迟应用确保DOM已渲染
	setTimeout(() => {
		if (isDark) {
			// 深色模式：使用纯黑色配色
			const darkNavbar = '#000000'  // 纯黑色导航栏
			const darkSidebar = '#000000'  // 纯黑色侧边栏
			const darkLogo = '#000000'     // 纯黑色Logo
			
			// 更新导航栏背景色 - 纯黑色模式
			const navbar = document.querySelector('.navbar')
			if (navbar) {
				navbar.style.setProperty('background', darkNavbar, 'important')
			}
			
			// 更新侧边栏背景色 - 纯黑色模式
			const sidebar = document.querySelector('.sidebar-container')
			if (sidebar) {
				sidebar.style.setProperty('background', darkSidebar, 'important')
			}
			
			// 更新Logo背景色 - 纯黑色模式
			const logo = document.querySelector('.sidebar-logo-container')
			if (logo) {
				logo.style.setProperty('background', darkLogo, 'important')
			}
			
			// 更新现代侧边栏 - 纯黑色模式
			const modernSidebar = document.querySelector('.modern-sidebar')
			if (modernSidebar) {
				modernSidebar.style.setProperty('background', darkSidebar, 'important')
			}
			
			// 更新CSS变量 - 深色模式
			const root = document.documentElement
			root.style.setProperty('--navbar-bg-color', darkNavbar)
			root.style.setProperty('--sidebar-bg-color', darkSidebar)
			root.style.setProperty('--page-bg-color', '#000000')
			
			// 暗黑模式下设置表格悬停颜色（微弱白色高亮）
			root.style.setProperty('--table-hover-bg-color', 'rgba(255, 255, 255, 0.05)')
		} else {
			// 浅色模式：使用主题配色
			// 更新导航栏背景色
			const navbar = document.querySelector('.navbar')
			if (navbar) {
				const navbarGradient = `linear-gradient(135deg, ${theme.navbar}bb 0%, ${theme.navbar}99 50%, ${theme.navbar}77 100%)`
				navbar.style.setProperty('background', navbarGradient, 'important')
			}
			
			// 更新侧边栏背景色 - 增强渐变效果
			const sidebar = document.querySelector('.sidebar-container')
			if (sidebar) {
				// 创建更丰富的渐变效果
				const lighterColor = adjustBrightness(theme.sidebar, 20) // 亮20%
				const darkerColor = adjustBrightness(theme.sidebar, -30)  // 暗30%
				const sidebarGradient = `linear-gradient(180deg, ${lighterColor} 0%, ${theme.sidebar} 35%, ${darkerColor} 100%)`
				sidebar.style.setProperty('background', sidebarGradient, 'important')
			}
			
			// 更新Logo背景色 - 与侧边栏渐变协调
			const logo = document.querySelector('.sidebar-logo-container')
			if (logo) {
				const logoLighterColor = adjustBrightness(theme.sidebar, 25) // 稍微更亮一些
				const logoDarkerColor = adjustBrightness(theme.sidebar, -20)  // 稍微暗一些
				const logoGradient = `linear-gradient(180deg, ${logoLighterColor} 0%, ${theme.sidebar} 50%, ${logoDarkerColor} 100%)`
				logo.style.setProperty('background', logoGradient, 'important')
			}
			
			// 更新现代侧边栏 - 增强渐变效果
			const modernSidebar = document.querySelector('.modern-sidebar')
			if (modernSidebar) {
				const modernLighterColor = adjustBrightness(theme.sidebar, 20) // 亮20%
				const modernDarkerColor = adjustBrightness(theme.sidebar, -30)  // 暗30%
				const modernSidebarGradient = `linear-gradient(180deg, ${modernLighterColor} 0%, ${theme.sidebar} 35%, ${modernDarkerColor} 100%)`
				modernSidebar.style.setProperty('background', modernSidebarGradient, 'important')
			}
			
			// 更新CSS变量 - 浅色模式
			const root = document.documentElement
			root.style.setProperty('--navbar-bg-color', theme.navbar)
			root.style.setProperty('--sidebar-bg-color', theme.sidebar)
			root.style.setProperty('--page-bg-color', theme.background)
			
			// 设置表格悬停颜色（侧边栏颜色的半透明版本）
			const sidebarRgb = hexToRgb(theme.sidebar)
			const hoverColor = `rgba(${sidebarRgb[0]}, ${sidebarRgb[1]}, ${sidebarRgb[2]}, 0.15)`
			root.style.setProperty('--table-hover-bg-color', hoverColor)
		}
		
		// 发送主题更新事件，包含表格主题信息
		const currentTableTheme = getTableThemeFromPrimaryColor(theme.navbar || theme.sidebar || '#6366f1')
		const event = new CustomEvent('themeFullUpdate', { 
			detail: { 
				...theme, 
				isDark, 
				tableTheme: currentTableTheme,
				tableThemeName: TABLE_THEMES[currentTableTheme]?.name
			} 
		})
		window.dispatchEvent(event)
	}, 200)
}

// 注意：TABLE_THEMES 仍然需要保留，因为预设主题会自动选择对应的表格主题

// 调整颜色亮度 - 用于创建渐变效果
function adjustBrightness(color, percent) {
	// 移除 # 号
	const hex = color.replace('#', '')
	
	// 转换为 RGB
	const r = parseInt(hex.substring(0, 2), 16)
	const g = parseInt(hex.substring(2, 4), 16)
	const b = parseInt(hex.substring(4, 6), 16)
	
	// 调整亮度
	const newR = Math.max(0, Math.min(255, Math.round(r + (r * percent / 100))))
	const newG = Math.max(0, Math.min(255, Math.round(g + (g * percent / 100))))
	const newB = Math.max(0, Math.min(255, Math.round(b + (b * percent / 100))))
	
	// 转换回 hex
	const toHex = (c) => {
		const hex = c.toString(16)
		return hex.length === 1 ? '0' + hex : hex
	}
	
	return `#${toHex(newR)}${toHex(newG)}${toHex(newB)}`
}

// hex颜色转rgb颜色
export function hexToRgb(str) {
	str = str.replace('#', '')
	let hexs = str.match(/../g)
	for (let i = 0; i < 3; i++) {
		hexs[i] = parseInt(hexs[i], 16)
	}
	return hexs
}

// rgb颜色转Hex颜色
export function rgbToHex(r, g, b) {
	let hexs = [r.toString(16), g.toString(16), b.toString(16)]
	for (let i = 0; i < 3; i++) {
		if (hexs[i].length == 1) {
			hexs[i] = `0${hexs[i]}`
		}
	}
	return `#${hexs.join('')}`
}

// 变浅颜色值
export function getLightColor(color, level) {
	let rgb = hexToRgb(color)
	for (let i = 0; i < 3; i++) {
		rgb[i] = Math.floor((255 - rgb[i]) * level + rgb[i])
	}
	return rgbToHex(rgb[0], rgb[1], rgb[2])
}

// 变深颜色值
export function getDarkColor(color, level) {
	let rgb = hexToRgb(color)
	for (let i = 0; i < 3; i++) {
		rgb[i] = Math.floor(rgb[i] * (1 - level))
	}
	return rgbToHex(rgb[0], rgb[1], rgb[2])
}
